package com.small.nacos.sys.utils;

import com.alibaba.nacos.common.utils.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author zhoujin
 * @Date 2022/11/5 10:41
 */
public class IPUtil {

    public static final String IP_PORT_SPLITER = ":";

    public static final String IPV6_START_MARK = "[";

    public static final String IPV6_END_MARK = "]";

    public static String[] splitIPPortStr(String str) {
        return str.split(IP_PORT_SPLITER);
    }

    private static final String IPV4_TUPLE = "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])";

    private static final Pattern IPV4_PATTERN = Pattern
            .compile("(?<!\\d)" + IPV4_TUPLE + "\\." + IPV4_TUPLE + "\\." + IPV4_TUPLE + "\\." + IPV4_TUPLE + "(?!\\d)");

    private static final Pattern IPV6_STD_PATTERN = Pattern
            .compile("^" + "(?:[0-9a-fA-F]{1,4}:){7}" + "[0-9a-fA-F]{1,4}" + "$");

    /**
     * 从包含IP地址的字符串中解析IP
     * @param str
     * @return
     */
    public static String getIPFromString(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        String result = "";
        if (StringUtils.containsIgnoreCase(str, IPV6_START_MARK) && StringUtils.containsIgnoreCase(str, IPV6_END_MARK)) {
            result = str.substring(str.indexOf(IPV6_START_MARK), (str.indexOf(IPV6_END_MARK) + 1));
            if (!isIPv6(result)) {
                result = "";
            }
        } else {
            Matcher m = IPV4_PATTERN.matcher(str);
            if (m.find()) {
                result = m.group();
            }
        }
        return result;
    }

    public static boolean isIPv6(String addr) {
        return isIPv6Address(removeBrackets(addr));
    }

    public static String removeBrackets(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        return str.replaceAll("[\\[\\]]", "");
    }

    public static boolean isIPv6Address(final String input) {
        return isIPv6StdAddress(input);
    }

    public static boolean isIPv6StdAddress(final String input) {
        return IPV6_STD_PATTERN.matcher(input).matches();
    }
}
